package com.bw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.TUser;
import com.bw.service.TUserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

/**
 * @author bobo棒
 * @date 2023年12月20日 9:10
 */

@RequestMapping("auth")
@RestController
public class AuthController {
    @Autowired
    TUserService tUserService;

    @RequestMapping("login")
    public Result login(@RequestBody TUser tUser){

        LambdaQueryWrapper<TUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUser::getUsername, tUser.getUsername());
        TUser dbUser = tUserService.getOne(wrapper);
        if(null ==dbUser){
            return Result.fail("无此用户");
        }

        String md5Hex = DigestUtil.md5Hex(tUser.getPassword() + salt);
        if(!dbUser.getPassword().equals(md5Hex)){
            return Result.fail("密码错误");
        }
        String token = JWTUtils.createToken(dbUser.getId() + "", 4 * 60);
        return Result.success(token);
    }



    public static final String salt="2109a";
    @PostConstruct//该注解 当项目启动时,会自动运行该方法
    public void initPWD(){
        String pwd="123";
        String md5Hex = DigestUtil.md5Hex(pwd + salt);
        System.out.println("初始化密码是:"+md5Hex);
    }
}
